package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.github.pagehelper.PageHelper;
import com.ruoyi.framework.mybatis.InsertBatchInjector;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Properties;

/**
 * @author : hcl
 * @Date : 2023/8/9 17:21
 */
@Component
@EnableTransactionManagement(proxyTargetClass = true)
public class MyBatisPlusConfig {
    /**
     * mybatis 分页插件配置
     */
//    @Bean
//    public PageHelper pageHelper() {
//        PageHelper pageHelper = new PageHelper();
//        Properties p = new Properties();
//        //设置为true时，会将RowBounds第一个参数offset当成pageNum页码使用
//        p.setProperty("offsetAsPageNum", "true");
//        //设置为true时，使用RowBounds分页会进行count查询
//        p.setProperty("rowBoundsWithCount", "true");
//        //启用合理化时，如果pageNum<1会查询第一页，如果pageNum>pages会查询最后一页
//        p.setProperty("reasonable", "false");
//        pageHelper.setProperties(p);
//        return pageHelper;
//    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(paginationInnerInterceptor());
        // 乐观锁插件
        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
        // 阻断插件
        interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
        return interceptor;
    }

    /**
     * 批量插入
     * mapper 中添加 Integer insertBatchSomeColumn(Collection<CLASS> list)
     */
    @Bean
    public InsertBatchInjector insertInjector() {
        return new InsertBatchInjector();
    }

    /**
     * 乐观锁插件 https://baomidou.com/guide/interceptor-optimistic-locker.html
     */
    private OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
        return new OptimisticLockerInnerInterceptor();
    }

    /**
     * 如果是对全表的删除或更新操作，就会终止该操作 https://baomidou.com/guide/interceptor-block-attack.html
     */
    private BlockAttackInnerInterceptor blockAttackInnerInterceptor() {
        return new BlockAttackInnerInterceptor();
    }

    /**
     * 分页
     */
    private PaginationInnerInterceptor paginationInnerInterceptor() {
        PaginationInnerInterceptor interceptor = new PaginationInnerInterceptor();
        interceptor.setDbType(DbType.MYSQL);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        interceptor.setMaxLimit(100L);
        return interceptor;
    }
}
